package com.example.acceletracks;

import java.util.List;
import java.util.TreeMap;

import android.location.Location;
import android.util.Log;

import com.google.android.gms.maps.model.LatLng;

public class DistanceManager {
	
	public static final int RADIUS = 6400;
	
	public static TreeMap<Double, LatLng> sort(LatLng actualLatLng, AcceleHoles acH)
	{
		TreeMap<Double, LatLng> map = new TreeMap<Double, LatLng>();
		LatLng [] tab = acH.toArray();
		for(int i=0; i<acH.getLength(); i++)
		{
			double distance1 = calculateDistance(actualLatLng,tab[i]);
			map.put(distance1*1000, tab[i]);	
		}
		
		return map;
	}
	
	public static double calculateDistance(LatLng point1, LatLng point2)
	{
		double x= Math.toRadians(point1.latitude - point2.latitude);
		double y= Math.toRadians(point1.longitude - point2.longitude) * Math.cos(Math.toRadians((point1.latitude + point2.latitude)/2));
		double c= Math.sqrt(x*x + y*y);
		
		double d = c*RADIUS;
		
		return d;
	}
	
	/*public static double calculateDistance2(LatLng point1, LatLng point2) {

	    double latDistance = Math.toRadians(point1.latitude - point2.latitude);
	    double lngDistance = Math.toRadians(point1.longitude - point2.longitude);

	    double a = (Math.sin(latDistance / 2) * Math.sin(latDistance / 2)) +
	                    (Math.cos(Math.toRadians(point1.latitude))) *
	                    (Math.cos(Math.toRadians(point2.latitude))) *
	                    (Math.sin(lngDistance / 2)) *
	                    (Math.sin(lngDistance / 2));

	    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

	    return (RADIUS *c);

	}
*/	
	public static void logMap(TreeMap<Double, LatLng> map)
	{
		Double [] tab = map.keySet().toArray(new Double[map.size()]);
	
		for(int i=0; i<tab.length; i++)
		{
			Log.d("log", "" + tab[i]);
		}
	}

	public static boolean isClose(LatLng latlng, Handler dbHandler, float radius) {

		List<Location> locations = IOManager.convertLatLngToLocation(dbHandler.getList());
		Location loc = new Location("");
		loc.setLatitude(latlng.latitude);
		loc.setLongitude(latlng.longitude);
				
		for (Location location : locations) {
			
			if(location.distanceTo(loc)>(radius/2))
				continue;
			else
				return true;			
		}
		
		return false;
	}

}
